package com.liurong.createpattern.prototype;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;

/**
 * 原型模式
 * @author liu.r
 *
 */
public class Prototype implements Cloneable, Serializable {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	
	/**
	 * 浅复制
	 * 		将一个对象复制后，基本数据类型的变量都会重新创建，而引用类型，指向的还是原对象所指向的
	 * @return
	 */
	public Object cloneShallow() {
		Prototype object = null;
		try {
			object  = (Prototype) super.clone();
		} catch (CloneNotSupportedException e) {
			e.printStackTrace();
		}
		return object;
	}
	
	/**
	 * 深复制
	 * 		将一个对象复制后，不论是基本数据类型还有引用类型，都是重新创建的
	 * @return
	 */
	public Object cloneDeep() throws IOException, ClassNotFoundException {
		// 写入当前对象的二进制
		ByteArrayOutputStream bos = new ByteArrayOutputStream();
		ObjectOutputStream oos = new ObjectOutputStream(bos);
		oos.writeObject(this);
		oos.close();
		
		// 读出二进制流产生新的对象
		ByteArrayInputStream bis = new ByteArrayInputStream(bos.toByteArray());
		ObjectInputStream ois = new ObjectInputStream(bis);
		Object object = ois.readObject();
		ois.close();
		
		return object;
	}
	
	private int num;
	private String string;
	private int arr[];
	public int getNum() {
		return num;
	}
	public void setNum(int num) {
		this.num = num;
	}
	public String getString() {
		return string;
	}
	public void setString(String string) {
		this.string = string;
	}
	public int[] getArr() {
		return arr;
	}
	public void setArr(int[] arr) {
		this.arr = arr;
	}
}
